package cn.itcast.controller;

import cn.itcast.pojo.Result;
import cn.itcast.utils.OSSUtils;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private OSSUtils ossUtils;
    /**
     * 上传文件
     * @param file 前端传入文件格式为MultipartFile
     * @return Result封装成前端要求的结果对象
     */
    @PostMapping
    public Result upload(MultipartFile file) throws ClientException {
        //得到上传图片云路径
        String upload = ossUtils.upload(file);
        //打印路径验证
        log.warn("上传的文件名字是:{}",upload);
        //返回结果,如果为空上传失败
        return upload != null ? Result.success("success",upload) : Result.error("上传失败");
    }
    private String randomSubDirectory(String originalFilename) {
        int hash = originalFilename.hashCode();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int subDir = hash & 15;
            stringBuilder.append(subDir + "/");

            hash >>= 4;
        }
        return stringBuilder.toString();
    }

    /*@PostMapping
    public void upload(MultipartFile photo) throws IOException {
        //读取上传文件的原始名称originalFilename
        String originalFilename = photo.getOriginalFilename();
        //上传时name的键名字
        String name = photo.getName();
        //创建一个目录
        File file = new File("d:/upload");
        if (!file.exists()){
            file.mkdir();
        }
        //创建一个子目录
        String subDirs = randomSubDirectory(originalFilename);
        file = new File(file, subDirs);
        if (!file.exists()){
            file.mkdirs();
        }
        //将文件以新的名称放入文件夹,随机前缀+"_"+originalFilename随机生成一个文件名,file存放的文件名
        photo.transferTo(new File(file, UUID.randomUUID().toString()+"_"+originalFilename));
        log.warn("上传的文件名字是:{}:{}",originalFilename,name);
        System.out.println("我是后台用于处理请求数据的接口");
    }

    private String randomSubDirectory(String originalFilename) {
        int hash = originalFilename.hashCode();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int subDir = hash & 15;
            stringBuilder.append(subDir + "/");

            hash >>= 4;
        }
        return stringBuilder.toString();
    }*/

}
